//
//  FunnyOfTheDayViewController.m
//  FunnyOfTheDay
//
//  Created by Giorgi Gioshvili on 3/22/09.
//  Copyright FSS 2009-2010. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#include <unistd.h>

#import "FunnyOfTheDayViewController.h"
#import "ImageLoader.h"

@implementation FunnyOfTheDayViewController

@synthesize infoView, imagePicker, imageView, imageSubmitFormView, imageSubmitUploadingView, infoButtonView, infoPanel;
@synthesize dateLabel, loadingPane, nextButton, prevButton, progressBar;
@synthesize imageDescriptionLabel, imageDateLabel, imageSizeLabel, imageSourceLabel, upperToolBar, downToolBar;
@synthesize submitImageDescriptionTextField, submitImageSourceTextField, submitImageEmailTextField;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    //Set some global cache settings (the memory will leak without these)
    [[NSURLCache sharedURLCache] setMemoryCapacity:0];
	[[NSURLCache sharedURLCache] setDiskCapacity:0]; 

	//Load the default Image
	NSBundle * mainBundle = [NSBundle mainBundle];
	NSString * imagePath = [mainBundle pathForResource:@"background-logo" ofType:@"png"];
	UIImage * defaultImage = [UIImage imageWithContentsOfFile:imagePath];
	CGRect rect = CGRectMake(0, 0, 320, 480);
	imageView = [[UIImageView alloc] initWithFrame:rect];
	[self.view insertSubview:imageView atIndex:0];
	imageView.image = defaultImage;

	//Add info view panel
	[self.view addSubview:infoPanel];
	infoPanel.hidden = true;

	//Add Image Submit Form View
	[self.view addSubview:imageSubmitFormView];
	imageSubmitFormView.hidden = true;
	[self.view addSubview: imageSubmitUploadingView];
	imageSubmitUploadingView.hidden = true;

    //Set the current date label on the intro screen
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterLongStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateLabel setText: [dateFormatter stringFromDate:[NSDate date]]];
    [dateFormatter release];

    //Show the "loading..." pane
    loadingPane.hidden = false;
    
    //Schedule the operations of getting the image ids and loading the first image
    [NSTimer scheduledTimerWithTimeInterval: 0.5
                                     target: self
                                   selector: @selector(viewDidLoadAndIsDisplayed:)
                                   userInfo: nil
                                    repeats: NO];
    
}

- (void) viewDidLoadAndIsDisplayed:(NSTimer *)timer
{
    [self refreshTheListOfImageIdsFromServer];
    [self loadImage:kNavigationNone];
}


- (void)refreshTheListOfImageIdsFromServer {
    
    if (pictureIds != NULL ) {
        [pictureIds release];
        pictureIds = NULL;
	}
    
    NSString *getIdsURL = [[NSString stringWithFormat:@"http://www.daily-giggle.net/php/get_approved_image_ids.php?order_by=%@&max_rows=%d", 
                            SORT_ORDER_BY_PUBLISH_DATE, MAX_PICTURES]
                           stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
	
	NSString * idList = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:getIdsURL]];
	
	if ( idList != nil ) {
		pictureIds = [[NSArray alloc] initWithArray:[idList componentsSeparatedByString:@"|"]];
	}
	else {
		NSString * msg = [[NSString alloc] initWithFormat:@"Error code: %d", 005];
		UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Unable to connect to the Server! Please, check your network connection and try again" 
														 message:msg
														delegate:self
											   cancelButtonTitle:@"Ok"
											   otherButtonTitles:nil];
		[alert show];
		[alert release];
		[msg release];
	}
		
	currentPictureIndex = 0;
    [idList release];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (YES);
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
//	self.view.frame = CGRectMake(0, 0, 320, 480);	//TODO - remove this line after most users have upgraded to iPhone 3.0
//	NSLog([NSString stringWithFormat:@"%f, %f, %f, %f", self.view.frame.origin.x, self.view.frame.origin.y, 
//														self.view.frame.size.width, self.view.frame.size.height]);
}

- (void)willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation 
													   duration:(NSTimeInterval)duration {
	[self resizeImageViewAsNeeded];
}

- (void)loadImage:(int)navigation {
    
	if ( pictureIds == NULL )
    {
		return;
	}
	NSUInteger count = [pictureIds count];
	if ( (currentPictureIndex < 0) || (currentPictureIndex >= count) )
	{
		return;
	}
	
	NSString * currentId = [pictureIds objectAtIndex: currentPictureIndex];
	
    //Load the image
    ImageLoader * imageLoader = [[ImageLoader alloc] init];
    NSError * imageLoaderError = [imageLoader loadImage:[[@"http://www.daily-giggle.net/php/get_image_by_img_id.php?img_id=" stringByAppendingString:currentId] 
                                  			  		      stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
                                        withProgressBar:progressBar];
    if ( imageLoaderError == nil ) {
    
        NSLog(@"Final size = %d\n", [[imageLoader receivedData] length]);
    	UIImage * image = [[UIImage alloc] initWithData:[imageLoader receivedData]];
	    imageView.image = image;
	    [self resizeImageViewAsNeeded];
	
    	//Load the title of the image
	    NSString * imageInfoURL = [[@"http://www.daily-giggle.net/php/get_image_info_by_id.php?img_id=" stringByAppendingString:currentId]
							   stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
        NSString * imageInfo = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:imageInfoURL]];
        NSArray * imageInfoItems = [imageInfo componentsSeparatedByString:@"|"];
        imageDescriptionLabel.text = [imageInfoItems objectAtIndex:1];
        imageDateLabel.text = [imageInfoItems objectAtIndex:3];
        imageSourceLabel.text = [imageInfoItems objectAtIndex:2];
        NSString * imageSizeAsText = [[NSString alloc] initWithFormat:@"%dkb", ([imageLoader.receivedData length]/1000)];
        imageSizeLabel.text = imageSizeAsText;
	
        //Let it slide in
        CATransition *animation = [CATransition animation];
        //[animation setDelegate:self];
        if (navigation == kNavigationLeft ) {
            [animation setType:kCATransitionPush];
            [animation setSubtype:kCATransitionFromLeft];
        }
        else 
        if ( navigation == kNavigationRight ) {
                [animation setType:kCATransitionPush];
                [animation setSubtype:kCATransitionFromRight];		
        }
        else
            if ( navigation == kNavigationNone ) {
            [animation setType:kCATransitionFade];
        }
	
        [animation setDuration:.5];
        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
        [imageView.layer addAnimation:animation forKey:@"fadeIn_02"];

        [image release];
        [imageInfo release];
        [imageSizeAsText release];

    }
    else {  //Error encountered while loading the image from URL
       
        NSString * msg = [[NSString alloc] initWithFormat:@"Error code: %d", imageLoader.lastError.code];
        UIAlertView * alert = [[UIAlertView alloc]	initWithTitle:@"Unable to load image!" 
                                                        message:msg
                                                        delegate:nil
                                               cancelButtonTitle:@"Ok"
                                               otherButtonTitles:nil];
        [alert show];
        [alert release];
        [msg release];
    }

    //Enable/Disable the prev/next arrow buttons as needed
    prevButton.enabled = (currentPictureIndex > 0);
    nextButton.enabled = (currentPictureIndex < count - 1);
    loadingPane.hidden = true;
    
    [imageLoader release];
    
}	

- (void)resizeImageViewAsNeeded {
	//UIImage * image = ((UIImageView *)self.view).image;
	CGSize imageSize = imageView.image.size;
	CGSize windowSize = self.view.superview.frame.size;

	//NSLog([NSString stringWithFormat:@"%f, %f, %f, %f", self.view.superview.frame.origin.x, self.view.superview.frame.origin.y, 
	//													windowSize.width, windowSize.height]);

	if ( self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
		 self.interfaceOrientation == UIInterfaceOrientationLandscapeRight ) {
		CGFloat tmp = windowSize.width;
		windowSize.width = windowSize.height;
		windowSize.height = tmp;
	}
	//windowSize.height -= 20;
	
	double ratioW = windowSize.width / imageSize.width;
	double ratioH = windowSize.height / imageSize.height;
	double ratio = MIN(ratioW, ratioH);
	imageSize.width *= ratio;
	imageSize.height *= ratio;
	CGRect rect = CGRectMake(((windowSize.width - imageSize.width)/2), ((windowSize.height - imageSize.height)/2), 
							  imageSize.width, imageSize.height);
	//self.view.bounds = rect;
	imageView.frame = rect;
	
	//Setup info panel
	infoPanel.frame = CGRectMake(1, windowSize.height - infoPanel.frame.size.height - downToolBar.frame.size.height, 
								 windowSize.width - 2, infoPanel.frame.size.height);
	for ( int i = 0; i < infoPanel.subviews.count; i++ ) {
		UIView * v = [infoPanel.subviews objectAtIndex:(i)];
		v.frame = CGRectMake(10, v.frame.origin.y, infoPanel.frame.size.width - 20, v.frame.size.height);
	}	

	//Setup Image Submit Form View
	imageSubmitFormView.frame = CGRectMake((windowSize.width - imageSubmitFormView.frame.size.width) / 2, 
										   (windowSize.height - imageSubmitFormView.frame.size.height) / 2, 
										    imageSubmitFormView.frame.size.width, imageSubmitFormView.frame.size.height);
	imageSubmitUploadingView.frame = CGRectMake((windowSize.width - imageSubmitUploadingView.frame.size.width) / 2, 
										   (windowSize.height - imageSubmitUploadingView.frame.size.height) / 2, 
										   imageSubmitUploadingView.frame.size.width, imageSubmitUploadingView.frame.size.height);
}

- (void)resetDisplay:(id)object {
	[loadingPane setNeedsDisplay];
	[self.view setNeedsDisplay];
	[imageSubmitUploadingView setNeedsDisplay];
	[imageSubmitFormView setNeedsDisplay];
}

- (IBAction)showInfo:(id)sender {

	CATransition * animation = [CATransition animation];
	[animation setDuration:0.25];
	[animation setType:kCATransitionPush];
	if ( infoPanel.hidden == true ) {
		[animation setSubtype:kCATransitionFromRight];
	}
	else {
		[animation setSubtype:kCATransitionFromLeft];
	}	
	[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
	[[infoPanel layer] addAnimation:animation forKey:@"SlideInfoPanel"];
	
	infoPanel.hidden = !infoPanel.hidden;
}

- (IBAction)prevImage:(id)sender {
	if ( currentPictureIndex > 0 ) {
		currentPictureIndex--;
		progressBar.progress = 0.0;
        loadingPane.hidden = false;
        [self loadImage:kNavigationLeft];
	}
}

- (IBAction)nextImage:(id)sender {
	if ( pictureIds == NULL )
	{
		return;
	}
	NSUInteger count = [pictureIds count];
	
	if ( currentPictureIndex < (count-1) )
	{
		currentPictureIndex++;
        progressBar.progress = 0.0;
		loadingPane.hidden = false;
        [self loadImage:kNavigationRight];
	}
}

- (IBAction)saveImage:(id)sender {
	UIImage * image = imageView.image;
	UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
	UIAlertView * alert = [[UIAlertView alloc]	initWithTitle:@"Image Saved" 
												message:@"Image Saved in Photo Gallery"
												delegate:nil
												cancelButtonTitle:@"Ok"
												otherButtonTitles:nil];
	[alert show];
	[alert release];
}

- (IBAction)submitImage:(id)sender {
	[self presentModalViewController:imagePicker animated:YES];
}

- (IBAction)submitImageTextEditDidFinish:(id)sender {
	[sender resignFirstResponder];
}

- (IBAction)submitImageSubmitClicked:(id)sender {
	
	//Update user settings (locally)
	[self saveUserSettings:submitImageEmailTextField.text];
    
    //Show the "Uploading..." indicator. The second line (NSRunLoop) is needed to let the current
    //thread's RunLoop object (message processor) to know there is a new input to be processed - the
    //"Uploading..." pane is now visible
    imageSubmitUploadingView.hidden = false;
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
	
	//Upload the image
	[self uploadImage];
}

- (void)uploadImage {
	
	//Resize the image to a lower resolution to make sure it is not taking too much space
	UIImage * img = imageView.image;
	float ratioW = 640 / img.size.width;
	float ratioH = 480 / img.size.height;
	float ratio = MIN(ratioW, ratioH);
	UIImage * resizedImage = [img scaleToSize:CGSizeMake(img.size.width * ratio, img.size.height * ratio):ratio];
	//UIImage * resizedImage = img; //[img scaleToSize:CGSizeMake(640, 480):ratio];
	NSLog(@"%f x %f", resizedImage.size.width, resizedImage.size.height);

	//Turning the image into a NSData object
	NSData * imageData = UIImageJPEGRepresentation(resizedImage, .5);
	NSString * urlString = @"http://www.daily-giggle.net/php/upload.php";

	//Setting up the request object now
	NSMutableURLRequest * request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:urlString]];
	[request setHTTPMethod:@"POST"];
	
	//Header data
	NSString * boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
	NSString * contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
	[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
	
	//Post body
	NSMutableData * body = [NSMutableData data];
	[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
	
	[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name= \"fuf_description\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
	[body appendData:[[NSString stringWithFormat:@"%@", submitImageDescriptionTextField.text] dataUsingEncoding:NSUTF8StringEncoding]];
	[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
	
	[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name= \"fuf_source\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
	[body appendData:[[NSString stringWithFormat:@"%@", submitImageSourceTextField.text] dataUsingEncoding:NSUTF8StringEncoding]];
	[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

	[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name= \"fuf_email\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
	[body appendData:[[NSString stringWithFormat:@"%@", submitImageEmailTextField.text] dataUsingEncoding:NSUTF8StringEncoding]];
	[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
	
	[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"fuf_file\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
	[body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
	[body appendData:[NSData dataWithData:imageData]];
	[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
	
	//Setting the body of the post to the reqeust
	[request setHTTPBody:body];
	
	//Now lets make the connection to the web
	NSData * returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	NSString * returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

	//Inform the user about the results
	NSRange htmlBodyStart = [returnString rangeOfString:@"<body>"];
	NSString * returnStringWithoutBodyStart = [returnString substringFromIndex:htmlBodyStart.location + htmlBodyStart.length];
	NSRange htmlBodyEnd = [returnStringWithoutBodyStart rangeOfString:@"</body>"];
	NSString * returnStringWithoutHtml = [returnStringWithoutBodyStart substringToIndex:htmlBodyEnd.location];
	
	UIAlertView * alert = [[UIAlertView alloc]	initWithTitle:@"Image Submitted" 
												message:returnStringWithoutHtml
												delegate:nil
												cancelButtonTitle:@"Ok"
												otherButtonTitles:nil];
	[alert show];
	[alert release];
	[returnString release];
	
	[self submitImageHideAndCleanUp];
}

- (NSString *)readUserSettings {
	
	NSUserDefaults * prefs = [NSUserDefaults standardUserDefaults];
	NSString * userEmail = [prefs stringForKey:@"userEmail"];
	
	return userEmail;
}

- (void)saveUserSettings:(NSString *)userEmail{

	NSUserDefaults * prefs = [NSUserDefaults standardUserDefaults];
	[prefs setObject:userEmail forKey:@"userEmail"];

}

- (IBAction)submitImageCancelClicked:(id)sender {
	[self submitImageHideAndCleanUp];
}

- (void)submitImageHideAndCleanUp {

	CATransition * animation = [CATransition animation];
	[animation setDuration:.25];
	[animation setType:kCATransitionPush];
	[animation setSubtype:kCATransitionFromTop];
	[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
	[[imageSubmitFormView layer] addAnimation:animation forKey:@"SlideImageSubmitFormView"];
	imageSubmitFormView.hidden = true;
	imageSubmitUploadingView.hidden = true;
	
	upperToolBar.userInteractionEnabled = true;
	downToolBar.userInteractionEnabled = true;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
	[picker dismissModalViewControllerAnimated:YES];

    imageView.image = image;
	[self resizeImageViewAsNeeded];
	
	NSString * userEmail = [self readUserSettings];
	submitImageEmailTextField.text = userEmail;
	
	CATransition * animation = [CATransition animation];
	[animation setDuration:.25];
	[animation setType:kCATransitionPush];
	[animation setSubtype:kCATransitionFromBottom];
	[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
	[[imageSubmitFormView layer] addAnimation:animation forKey:@"SlideImageSubmitFormView"];
	imageSubmitFormView.hidden = false;
	
	upperToolBar.userInteractionEnabled = false;
	downToolBar.userInteractionEnabled = false;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	[picker dismissModalViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	
	UITouch * touch = [touches anyObject];
	gestureStartPoint = [touch locationInView:self.view];
	
	if ( touch.view == self.view ) { 
		CATransition * upAnimation = [CATransition animation];
		CATransition * downAnimation = [CATransition animation];
		[upAnimation setDuration:.25];
		[downAnimation setDuration:.25];
		[upAnimation setType:kCATransitionFade];
		[downAnimation setType:kCATransitionPush];
		
		if ( downToolBar.hidden == true ) {
			//gg - commnted out, the last parameter is only supported in 3.2+
			//[[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
			
			[[UIApplication sharedApplication] setStatusBarHidden:NO];
			
			upperToolBar.hidden = false;
			downToolBar.hidden = false;
			
			[downAnimation setSubtype:kCATransitionFromTop];
		}
		else {
			//gg - commnted out, the last parameter is only supported in 3.2+
			//[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
			[[UIApplication sharedApplication] setStatusBarHidden:NO];

			upperToolBar.hidden = true;
			downToolBar.hidden = true;
			infoPanel.hidden = true;
			
			[downAnimation setSubtype:kCATransitionFromBottom];
		}
		
		[downAnimation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
		[upAnimation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
		
		[[upperToolBar layer] addAnimation:upAnimation forKey:@"UpperSlideToolBar"];
		[[downToolBar layer] addAnimation:downAnimation forKey:@"DownSlideToolBar"];
	}
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	if ( loadingPane.hidden == false ) {
		return;
	}
	
	UITouch *touch = [touches anyObject];
	CGPoint currentPosition = [touch locationInView:self.view];
	
	CGFloat diffX = gestureStartPoint.x - currentPosition.x;
	CGFloat deltaX = fabs(diffX);
	CGFloat deltaY = fabs(gestureStartPoint.y - currentPosition.y);
	

	if ( (deltaX >= kMinimumGestureLength) && (deltaY <= kMaximumVariance)) {
		//horizontal swipe
		if ( diffX < 0 ) {
			[self prevImage:nil];
	    }
		else {
			[self nextImage:nil];
	    }
	}
}

- (void)dealloc {
	//Dealloacte local objects
	[imageView release];
	[infoView release];
	[dateLabel release];
	[loadingPane release];
	if ( pictureIds != NULL ) {
		[pictureIds release];
	}
	
	//Deallocate super
    [super dealloc];
}

@end
